package cn.le.coap;

import com.alibaba.fastjson.JSONObject;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class Scheduler {

    private Random ra = new Random();
    @Scheduled(fixedRate = 2000)
    public void sendByte() throws URISyntaxException {
        System.out.println("senByte");
        //创建请求资源，201904151718 设备唯一编码，模拟imie 5683
        URI uri = new URI("coap://127.0.0.1:8989/iot-byte?201904151718");
        CoapClient client = new CoapClient(uri);

        StringBuilder sb = new StringBuilder();
        sb.append(ra.nextInt(999)%(999-100+1)+100);
        sb.append(new BigDecimal(ra.nextDouble()).setScale(2, BigDecimal.ROUND_HALF_UP));
        //请求资源
        CoapResponse response = client.post(sb.toString(), MediaTypeRegistry.TEXT_PLAIN);
        System.out.println("sendByte发送---"+sb.toString());
        if(response !=null){
            System.out.println(response.getCode());  //请求状态码
            System.out.println(response.getOptions());  //选项参数
            System.out.println(response.getResponseText());  //内容文本信息
            System.out.println(Utils.prettyPrint(response));  //报文内容
        }
    }

    @Scheduled(fixedRate = 2000)
    public void sendJson() throws URISyntaxException {
        URI uri =  new URI("coap://127.0.0.1:8989/iot-json?2019041717");  //创建一个资源请求hello资源，注意默认端口为5683
        CoapClient client = new CoapClient(uri);
        //温度
        int temperature = ra.nextInt(999)%(999-100+1)+100;
        //湿度
        String humidity = String.valueOf(new BigDecimal(ra.nextDouble()).setScale(2, BigDecimal.ROUND_HALF_UP));
        Map map = new HashMap<String,String>();
        map.put("T",String.valueOf(temperature));
        map.put("H",humidity);
        String json = JSONObject.toJSONString(map);
        client.post(json,MediaTypeRegistry.TEXT_PLAIN);

        System.out.println("sendJson发送---" + json);

    }


}

